import {ref} from 'vue'
import { getRealSizeByStr, getFileSizeStr, getNeedTime } from '@/utils'
import { useFakeDownload} from '@/stores/fake-download'
import { storeToRefs } from 'pinia';

const useFakeDownloadHook = () => {
  const timeoutMao: Record<string, any> = ref({});//定时器map
  
  const fakeDownloadStore = useFakeDownload();
  const { showDialog,closeDialogTime}=storeToRefs(fakeDownloadStore)
  
  const startOne = (key: string,callback: () => void) => {//开始某一个
    if (timeoutMao.value[key].currentAllSize > timeoutMao.value[key].finishSize) {//已经无法继续定时，
      timeoutMao.value[key].item.status = '3';
      timeoutMao.value[key].item.errorMsg='网络故障'
      timeoutMao.value[key].item.needTimeStr = '-- : -- : --';
      timeoutMao.value[key].timeout = null;//定时器清空
      callback();
      return;
    } else {
      timeoutMao.value[key].item.status = '1';
    }
    const timeout = 1000 + 1000 * Math.random();
    callback();
    timeoutMao.value[key].timeout = window.setTimeout(() => {
      const unitSize = (10 + 20 * Math.random()) * 1024 ;//每次增加10-30kb
      // if (timeoutMao.value[key].item.percent > 70) {
      //   unitSize = (10 + 10 * Math.random()) * 1024 ;//每次增加4-8mb
      // }else if (timeoutMao.value[key].item.percent>60) {
      //   unitSize = (100 + 100 * Math.random()) * 1024 ;//每次增加4-8mb
      // }else if (timeoutMao.value[key].item.percent>30) {
      //   unitSize = (1 + 1 * Math.random()) * 1024 * 1024;//每次增加4-8mb
      // }
     
      timeoutMao.value[key].currentAllSize += unitSize;
      // timeoutMao.value[key].currentSegmentSize+=unitSize;
      const currentTime = (new Date()).getTime();
      const diffTime = (currentTime - timeoutMao.value[key].time) / 1000;
      const speed = parseFloat((unitSize / diffTime).toFixed(2));//速度
      const allTime = (timeoutMao.value[key].allSize / speed) >> 0;//总的时间

      timeoutMao.value[key].item.downloadSpeed = speed;
      timeoutMao.value[key].item.downloadSpeedStr = getFileSizeStr(speed);
      timeoutMao.value[key].item.needTime = allTime;
      timeoutMao.value[key].item.needTimeStr = getNeedTime(allTime);
      timeoutMao.value[key].item.currentSize = parseFloat((timeoutMao.value[key].currentAllSize).toFixed(2));
      timeoutMao.value[key].item.currentSizeStr = getFileSizeStr(timeoutMao.value[key].item.currentSize);
      timeoutMao.value[key].item.percent = parseFloat((timeoutMao.value[key].currentAllSize / timeoutMao.value[key].allSize* 100).toFixed(0)) 

      timeoutMao.value[key].time=currentTime
      if (timeoutMao.value[key].currentAllSize < timeoutMao.value[key].finishSize) {//小于片段长度，可以继续定时
        // if (timeoutMao.value[key].item.percent>=30&&!timeoutMao.value[key].item.fake_user_overload_30) {
        //   timeoutMao.value[key].item.fake_user_overload_30 = true;
        //   timeoutMao.value[key].item.status = '6';
        // }
        // if (timeoutMao.value[key].item.percent>=60&&!timeoutMao.value[key].item.fake_user_overload_60) {
        //   timeoutMao.value[key].item.fake_user_overload_60 = true;
        //   timeoutMao.value[key].item.status = '6';
        // }
        const currentTime = (new Date()).getTime();
        const startTime = timeoutMao.value[key].item.fake_start_time;
        const timeout = timeoutMao.value[key].item.fake_time_out;
        const isOverTime = (currentTime - startTime) > timeout;//超过时间了

        let getDialog = false;//是否得到弹出框
        if (isOverTime&&!showDialog.value) {
          if ((closeDialogTime.value === 0) || (currentTime - closeDialogTime.value > 5000)) {//之前没有弹出过，或者距离上次弹出超过了5s
            timeoutMao.value[key].item.status = '4'
            timeoutMao.value[key].item.needTime = 0;
            timeoutMao.value[key].item.needTimeStr = '-- : -- : --';
            getDialog = true;
          }
        }
        if (isOverTime && !getDialog) {//超过时间，但是没有得到弹出框，重新开始计时
          timeoutMao.value[key].item.fake_start_time = (new Date()).getTime();
          timeoutMao.value[key].item.fake_time_out = (5 + 5 * Math.random()) * 1000;
        }
        if (timeoutMao.value[key].item.status!=='4') {//中断
          startOne(key,callback);
        } else {
          callback();
        }
      } else {//超过片段长度，暂停
        timeoutMao.value[key].item.status = '3';
        timeoutMao.value[key].item.errorMsg='网络故障'
        timeoutMao.value[key].timeout = null;//定时器清空
        timeoutMao.value[key].item.downloadSpeed = 0;
        timeoutMao.value[key].item.needTime = 0;
        timeoutMao.value[key].item.needTimeStr = '-- : -- : --';
        // timeoutMao.value[key].currentSegmentSize = 0;
        callback();
      }
    },timeout)
      
  }
  const startAll = (callback: () => void) => {//全部开始
    for (const key in timeoutMao.value) {
      startOne(key,callback);
    }
  }
  const pauseOne = (key: string) => {//暂停某一个
    if (timeoutMao.value[key]) {
      timeoutMao.value[key].item.status = '4'
      timeoutMao.value[key].item.needTime = 0
      timeoutMao.value[key].item.needTimeStr='-- : -- : --'
      timeoutMao.value[key].item.downloadSpeed = 0
      timeoutMao.value[key].item.downloadSpeedStr='0KB'
      if (timeoutMao.value[key].timeout) {
        clearTimeout(timeoutMao.value[key].timeout)
      }
    }
  }
  const pauseAll = () => {//全部暂停
    for (const key in timeoutMao.value) {
      pauseOne(key);
    }
  }
  const deleteOne=(key:string) => {// 删除一个
    if (timeoutMao.value[key]) {
      if (timeoutMao.value[key].timeout) {
        clearTimeout(timeoutMao.value[key].timeout)
      }
      delete timeoutMao.value[key];
    }
  }
  const delteAll = () => {//全部删除
    for (const key in timeoutMao.value) {
      deleteOne(key);
    }
  }

  const initOne = (item: any) => {//初始化
    const downloadKey = Math.random().toString(36).slice(2) + (new Date()).getTime().toString(36).slice(2);
    if (!timeoutMao.value[downloadKey]) {
      const allSize = item.allSize;
      const finishSize = parseFloat(((80 + 10 * Math.random() >> 0) *0.01* allSize).toFixed(2));//最终的size
      // const segmentCount = 5 + (Math.random() * 5) >> 0;//把最终的size，分成多少段，每一段达到后，就会停止
      
      // const segmentSize=parseFloat((finishSize / segmentCount).toFixed(2));//每一段的size

      timeoutMao.value[downloadKey] = {
        item,
        allSize,//总size
        finishSize,//最终达到这个size，停止
        currentAllSize: 0,//当前总的size
        // currentSegmentSize:0,//当前这个片段的size
        time:(new Date()).getTime(),
        timeout:null
      };

    }
    return downloadKey;
  }
  
  return {
    initOne,
    startOne,
    startAll,
    pauseOne,
    pauseAll,
    deleteOne,
    delteAll
  }
}

export default useFakeDownloadHook;